define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'pagination', 'autocomplete', 'filesaver', 'editor', 'fileupload', 'js/service/agupload'], function(app) {
    'use strict';
    /*manage knowledgeproperty*/
    app.controller('Knowledgeproperty', function($scope, crmConst, $rootScope, dataFactoryCRM, $q, $compile, Upload, $http, $timeout, AgUpload) {
        $rootScope.editfilesparam = { fileEdit: [], edit_file_original_name: [], edit_arrfile: [] };
        $rootScope.editimage = {};
        $rootScope.thirdurlimg = {};
        $rootScope.secondTabFile = {};
        $rootScope.addfilesparam = { addfiles: [], add_file_original_name: [], add_arrfile: [] };
        $rootScope.img = {};
        $rootScope.urlimg = {};
        $rootScope.secondupload = {};
        $scope.img = {};
        $scope.urlfirstimg = {};
        $scope.addfiles = new Array();
        $scope.param = { arrfile: [], file_original_name: [] };
        $scope.editparam = { edit_arrfile: [], edit_file_original_name: [] };
        $scope.editimg = {};
        $scope.tab = {};
        $scope.total = {};
        $scope.editfile = {};
        $scope.KnowledgeSource = {};
        $scope.thirddisplayimg = {};
        $scope.thirdparam = {};
        $scope.multiplefilesupload = { multiplefiles: [] };
        $scope.viewknowledgemsg = {};
        $scope.is_uploading;
        $scope.is_uploadingimg;
        $scope.is_edituploadingimg;
        $scope.is_edituploading;
        $scope.shownodepath;
        $scope.loginuserid;
        $scope.judge = 0;
        $scope.is_hide = 2;
        $scope.is_picture;
        $scope.editparamSecondTab;
        $scope.knowledge_id;
        $scope.knowledge_spot_id;
        $scope.addknowledgeid;
        $scope.firstimg;
        $scope.verify = '';
        $scope.tabcondition;
        $scope.getresult;
        $scope.chkdisabled = true;
        $scope.thirdchkdisabled = true;
        $scope.editchkdisabled = false;
        $scope.editthirdchkdisabled = false;
        $scope.tabselected = 'first';
        $scope.viewknowledgenode = 'viewknowledgenode';
        $scope.seturls = 'knowledgeproperty/uploadmultiplefiles';
        $scope.newarray = new Array();
        $scope.knowledgeproperty = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            // pageSize: 2,
            k: 3
        };

        //get Login User Id
        $scope.getuserid = function() {
            dataFactoryCRM.getDataByAPI('Knowledgeproperty/LoginUserId').then(function(d) {
                if (d.rcode == 1) {
                    $scope.loginuserid = d.data;
                    // console.log(d.data);
                } else {
                    // 
                }
            });
        }

        $scope.getuserid();

        // show knowledgeRight list
        $scope.KnowledgeRightList = function() {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeproperty/GetKnowledgeData').then(function(d) {
                if (d.rcode == 1) {
                    $scope.KnowledgeNodeTree(d.data);
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // show node path
        $scope.shownode = function(k) {
            var deferred = $q.defer();
            dataFactoryCRM.postDataByAPI('Knowledgeproperty/ShowNode', { knowledge_spot_id: k }).then(function(d) {
                // console.log(d);
                if (d.rcode == 1) {
                    deferred.resolve(d.data);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        //display knowledgeproperty list
        $scope.KnowledgeDatalist = function() {
            if ($scope.tabcondition) {
                $scope.knowledge_id = $scope.tabcondition;
                $scope.param.knowledge_spot_id = $scope.tabcondition;
                $scope.shownode($scope.tabcondition).then(function(d) {
                    // console.log(d);
                    $scope.shownodepath = d;
                });
                // var url = "Knowledgeproperty/index";
                // url += '?' + $.param($scope.param) + "&psize=" + $scope.knowledgeproperty.pageSize + "&p=" + $scope.knowledgeproperty.pageNow;
                // dataFactoryCRM.getDataByAPI(url).then(function(_d) {
                dataFactoryCRM.postDataByAPI('Knowledgeproperty/index', { knowledge_spot_id: $scope.param.knowledge_spot_id, psize: $scope.knowledgeproperty.pageSize, p: $scope.knowledgeproperty.pageNow }).then(function(_d) {
                    if (_d.rcode == 1) {
                        $scope.knowledgeproperty.pageSize = _d.psize;
                        $scope.knowledgeproperty.pageAll = _d.pall;
                        $scope.knowledgeproperty.pageNow = _d.p;
                        $scope.knowledgepropertysource = _d.data;
                        $scope.is_picture = _d.is_picture;
                        $scope.is_hide = _d.is_hide;
                        // console.log($scope.is_hide);
                    } else {
                        $scope.is_picture = _d.is_picture;
                        $scope.knowledgepropertysource = '';
                        $scope.knowledgeproperty.pageAll = 0;
                        $scope.is_hide = _d.is_hide;
                    }
                });
            } else {
                setTimeout(function() { //why need twice settimeout
                    $scope.KnowledgeRightList().then(function(d) {
                        $scope.KnowledgeSource = d.data;
                    });
                    $scope.is_picture = 1;
                }, 100)
            }
        }

        $scope.KnowledgeDatalist();

        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.KnowledgeDatalist();
        });

        // insert knowledge into knowledgeproperty 
        $scope.AddKnowledgeProperty = function() {
            function init() {
                $('#KnowLedge_id').form('clear');
                $rootScope.img.path = '';
                $scope.img.path = '';
                $scope.addfiles = [];
                $scope.param = {};
                $scope.uploadfile = '';
                $scope.urlfirstimg = '';
                $rootScope.addfilesparam.addfiles = [];
                $rootScope.addfilesparam.add_file_original_name = [];
                $rootScope.addfilesparam.add_arrfile = [];
                $rootScope.secondupload.view_path = '';
                $rootScope.secondupload.source_name = '';
            }
            init();
            setTimeout(function() {
                $('.ui.add.modal').modal('refresh');
            }, 100);
            $('.ui.add.modal').modal({
                closable: false,
                observeChanges: true,
                onApprove: function() {
                    if ($scope.tabselected == 'first') {
                        if ($('#KnowLedge_id').form('is valid')) {
                            $scope.imagesPost();
                        } else {
                            return false;
                        }
                    } else if ($scope.tabselected == 'second') {
                        // $('.ui.add.modal').modal('refresh');
                        if ($('#KnowLedge_id').form('is valid') && $rootScope.secondupload.view_path && $rootScope.secondupload.source_name) {
                            $scope.addUploadfile();
                        } else {
                            $('#add_sty').addClass('ui basic red pointing prompt label transition visible');
                            document.getElementById("add_sty").innerHTML = '请选择上传文件';
                            return false;
                        }
                    } else {
                        if ($('#KnowLedge_id').form('is valid')) {
                            $scope.knowledgeUrl();
                        } else {
                            return false;
                        }
                    }
                    setTimeout(function() {
                        return true;
                    }, 200);
                }
            }).modal('show');
        }

        // tab transport
        $scope.tab = function(k) {
            $scope.tabselected = k;
        }

        // judge if the file is pictrue
        $scope.IsPic = function(file) {
            var mime = /\.[^\.]+/.exec(file['name']);
            var imgExt = ['.gif', '.GIF', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', 'BMP', '.png', '.PNG', '.swf', '.SWF'];
            if (imgExt.indexOf(mime[0]) > -1)
                return true;
            else
                return false;
        }

        // add first img of page
        $scope.addImgChange = function(img) {
            if (img) {
                if ($scope.IsPic(img)) {
                    img.path = window.URL.createObjectURL(img);
                    $scope.img.path = img.path;
                }
                $scope.is_uploadingimg = true;
                $scope.multiple(img, $scope.seturls).then(function(d) {
                    $scope.is_uploadingimg = false;
                    $rootScope.img.path = d.view_path;
                    // console.log($rootScope.img.path);
                });
            }
        }

        // edit first img of page
        $scope.editImgChange = function(editimage) {
            if (editimage) {
                if ($scope.IsPic(editimage)) {
                    $scope.editimage.path = window.URL.createObjectURL(editimage);
                }
                $scope.is_edituploadingimg = true;
                $scope.multiple(editimage, $scope.seturls).then(function(d) {
                    $scope.is_edituploadingimg = false;
                    $rootScope.editimage.path = d.view_path;
                });
            }
        }

        // add third tab img
        $scope.addUrlImgChange = function(urlimg) {
            if (urlimg) {
                if ($scope.IsPic(urlimg)) {
                    urlimg.path = window.URL.createObjectURL(urlimg);
                    $scope.urlfirstimg = urlimg; //why added path is false;
                }
                $scope.is_uploadingimg = true;
                $scope.multiple(urlimg, $scope.seturls).then(function(d) {
                    $scope.is_uploadingimg = false;
                    $rootScope.urlimg.path = d.view_path;
                    // console.log($rootScope.img.path);
                });
            }
        }

        // edit third tab pic
        $scope.editUrlImgChange = function(thirdurlimg) {
            if (thirdurlimg) {
                if ($scope.IsPic(thirdurlimg)) {
                    // thirdurlimg.path = window.URL.createObjectURL(thirdurlimg);
                    $scope.thirdurlimg.path = window.URL.createObjectURL(thirdurlimg);
                }
                $scope.is_edituploadingimg = true;
                $scope.multiple(thirdurlimg, $scope.seturls).then(function(d) {
                    $scope.is_edituploadingimg = false;
                    $rootScope.thirdurlimg.path = d.view_path;
                });
            }
        }

        // watch third tab img
        $scope.$watch('urlfirstimg.path', function() {
            if ($scope.urlfirstimg.path) {
                $scope.thirdchkdisabled = false;
                // $("input[name='addthirdtabchk']").prop('checked', true);
                // $scope.param.thirdtabchk = 1;
            } else {
                $scope.thirdchkdisabled = true;
                $("input[name='addthirdtabchk']").prop('checked', false);
                $scope.param.thirdtabchk = 0;
            }
        })

        // watch first tab img
        $scope.$watch('img.path', function() {
            if ($scope.img) {
                if (!$scope.img.path) {
                    $("input[name='addfirsttabchk']").prop('checked', false);
                    $scope.param.checked = 0;
                    $scope.chkdisabled = true;
                } else {
                    // $("input[name='addfirsttabchk']").prop('checked', true);
                    // $scope.param.checked = 1;
                    $scope.chkdisabled = false;
                }
            }
        });

        // watch edit first tab img
        $scope.$watch('editimage.path', function() {
            if ($scope.editimage) {
                if (!$scope.editimage.path) {
                    $("input[name='firsteditcheckbox']").prop('checked', false);
                    $scope.editimage.editcheck = 0;
                    $scope.editchkdisabled = true;
                } else {
                    // $("input[name='firsteditcheckbox']").prop('checked', true);
                    // $scope.editimage.editcheck = 1;
                    $scope.editchkdisabled = false;
                }
            }
        });

        // watch edit third tab img
        $scope.$watch('thirdurlimg.path', function() {
            if ($scope.thirdurlimg) {
                if (!$scope.thirdurlimg.path) {
                    $("input[name='thirdcheckbox']").prop('checked', false);
                    $scope.thirdparam.urlexpression = 0;
                    $scope.editthirdchkdisabled = true;
                } else {
                    // $("input[name='thirdcheckbox']").prop('checked', true);
                    // $scope.thirdparam.urlexpression = 1;
                    $scope.editthirdchkdisabled = false;
                }
            }
        });

        //multiple files import error verify
        $scope.import_file_error = function(_msg) {
            $scope.import_pays_error = _msg;
            $timeout(function() {
                $scope.import_pays_error = '';
            }, 2000);
        };

        // watch add richcontent
        $scope.$watch('param.templete', function(nv, ov) {
            if (!nv || nv == '<p><br></p>') {
                $('#add_tempalte').val('');
            } else {
                $('#add_tempalte').val($scope.param.templete);
            }
        });

        // watch add richcontent
        $scope.$watch('editparam.content', function(nv, ov) {
            if (!nv || nv == '<p><br></p>') {
                $('#edit_tempalte').val('');
            } else {
                $('#edit_tempalte').val($scope.editparam.content);
            }
        });

        // add files of fisrt tab into array 
        $scope.addChange = function(file) {
            if (file) {
                $rootScope.addfilesparam.addfiles.push(file);
                $scope.is_uploading = true;
                $scope.multiple(file, $scope.seturls).then(function(d) {
                    $scope.is_uploading = false;
                    $rootScope.addfilesparam.add_file_original_name.push(d.source_name);
                    $rootScope.addfilesparam.add_arrfile.push(d.view_path);
                });
            } else {
                $scope.import_file_error("选择文件格式错误");
            }
        };

        // first tab editfile into array
        $scope.addeditchange = function(editfileupload) {
            if (editfileupload) {
                $rootScope.editfilesparam.fileEdit.push(editfileupload);
                $scope.is_edituploading = true;
                $scope.multiple(editfileupload, $scope.seturls).then(function(d) {
                    $scope.is_edituploading = false;
                    $rootScope.editfilesparam.edit_file_original_name.push(d.source_name);
                    $rootScope.editfilesparam.edit_arrfile.push(d.view_path);
                });
            } else {
                $scope.import_file_error("选择文件格式错误");
            }
        }

        // del firstimg
        $scope.delFirstImg = function() {
            $scope.img.path = '';
            $rootScope.img.path = '';
            $scope.editimage.path = '';
            $scope.urlfirstimg = '';
            $scope.thirdurlimg.path = '';
            $rootScope.editimage.path = '';
            $rootScope.thirdurlimg.path = '';
        }

        // del first tab files in array
        $scope.delFile = function() {
            var index = this.$index;
            $scope.addfilesparam.addfiles.splice(index, 1);
            $rootScope.addfilesparam.add_file_original_name.splice(index, 1);
            $rootScope.addfilesparam.add_arrfile.splice(index, 1);
            // console.log($scope.addfilesparam);
        }

        // del edit file in array
        $scope.delEditFile = function() {
            var index = this.$index;
            var count = $rootScope.editfilesparam.length;
            var num = index;
            $rootScope.editfilesparam.fileEdit.splice(index, 1);
            $rootScope.editfilesparam.edit_file_original_name.splice(index - count, 1);
            $rootScope.editfilesparam.edit_arrfile.splice(index - count, 1);
        }

        // del second tab file 
        $scope.delSecondTabFile = function() {
            $scope.editfile = ''
        }


        // display fisrt picture
        $scope.is_display = function() {
            if ($("input[name='addfirsttabchk']").prop('checked')) {
                $scope.param.checked = 1;
            } else {
                $scope.param.checked = 0;
            }
            // console.log($scope.param.checked);
        }

        // third tab checkbox
        $scope.thirdtabcheckbox = function() {
            if ($("input[name='addthirdtabchk']").prop('checked')) {
                $scope.param.thirdtabchk = 1;
            } else {
                $scope.param.thirdtabchk = 0;
            }
        }

        //edit is_first_display checkbox 
        $scope.editchecked = function() {
            if ($("input[name='firsteditcheckbox']").prop('checked')) {
                $scope.editparam.editcheck = 1;
            } else {
                $scope.editparam.editcheck = 0;
            }
        }

        $scope.editthirdtabcheckbox = function() {
            if ($("input[name='thirdcheckbox']").prop('checked')) {
                $scope.thirdparam.urlexpression = 1;
            } else {
                $scope.thirdparam.urlexpression = 0;
            }
        }

        // multiple files upload
        $scope.multiple = function(k, v) {
            var deferred = $q.defer();
            $scope.multiplefilesupload.multiplefiles = k;
            $scope.multiplefilesupload.name = 'multiplefiles';
            Upload.upload({
                url: crmConst.BASE + crmConst.API + v,
                data: $scope.multiplefilesupload
            }).then(function(_data) {
                $scope.multiplefilesupload.status = 1;
                if (_data && _data.status == 200) {
                    deferred.resolve(_data.data);
                } else
                    deferred.reject("上传失败");
            });
            return deferred.promise;
        }

        //add first tab msg
        $scope.imagesPost = function() {
            function addSuccess() {
                setTimeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }
            $scope.param.FirstImgPath = $rootScope.img.path;
            $scope.param.msg_type = 1;
            dataFactoryCRM.postDataByAPI('Knowledgeproperty/AddKnowdedge', { param: $scope.param, original_name: $rootScope.addfilesparam.add_file_original_name, view_path: $rootScope.addfilesparam.add_arrfile, knowledge_spot_id: $scope.knowledge_id }).then(function(d) {
                if (d) {
                    setTimeout(function() {
                        addSuccess();
                        $scope.KnowledgeDatalist();
                    }, 200)
                } else {
                    addFail();
                }
            });
        }

        // add second file upload
        $scope.addUpload = function(transfile) {
            if (transfile) {
                $scope.uploadfile = transfile;
                if (!$scope.param.filetitle) {
                    $scope.param.filetitle = transfile.name;
                }
                $scope.is_uploading = true;
                $scope.multiple(transfile, $scope.seturls).then(function(d) {
                    $scope.is_uploading = false;
                    $rootScope.secondupload.view_path = d.view_path;
                    $rootScope.secondupload.source_name = d.source_name;
                });
            } else {
                $scope.import_file_error("选择文件格式错误");
            }
        }

        // edit second file upload
        $scope.addUploadSecondTab = function(secondTabFile) {
            if (secondTabFile) {
                $rootScope.secondTabFile.name = secondTabFile.name;
                Object.defineProperties(secondTabFile, {
                    name: {
                        value: secondTabFile.name,
                        writable: true
                    },
                });
                $scope.is_edituploading = true;
                $scope.multiple(secondTabFile, $scope.seturls).then(function(d) {
                    $scope.is_edituploading = false;
                    $rootScope.secondTabFile.view_path = d.view_path;
                    $rootScope.secondTabFile.name = d.source_name;
                    // console.log($rootScope.secondTabFile);
                });
            } else {
                $scope.import_file_error("选择文件格式错误");
            }
        }

        // add second tab file upload
        $scope.addUploadfile = function() {
            function addSuccess() {
                setTimeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }

            $scope.param.fileTrans = $rootScope.secondupload.view_path;
            $scope.param.original_name = $rootScope.secondupload.source_name;
            $scope.param.msg_type = 2;

            dataFactoryCRM.postDataByAPI('Knowledgeproperty/AddFileUpload', { param: $scope.param, knowledge_spot_id: $scope.knowledge_id }).then(function(d) {
                if (d) {
                    setTimeout(function() {
                        addSuccess();
                        $scope.KnowledgeDatalist(d.condition);
                    }, 200)
                } else {
                    addFail();
                }
            });
        }

        //add url
        $scope.knowledgeUrl = function() {
            function addSuccess() {
                setTimeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }
            $scope.param.msg_type = 3;
            $scope.param.urlfirstimg = $rootScope.urlimg.path;
            dataFactoryCRM.postDataByAPI('Knowledgeproperty/urlUpload', { param: $scope.param, knowledge_spot_id: $scope.knowledge_id }).then(function(d) {
                if (d) {
                    setTimeout(function() {
                        addSuccess();
                        $scope.KnowledgeDatalist(d.condition);
                    }, 200)
                } else {
                    addFail();
                }
            });
        }

        // edit knowledgeproperty records
        $scope.editknowledge = function(k, v) {
            $rootScope.editfilesparam.edit_arrfile = [];
            $rootScope.editfilesparam.edit_file_original_name = [];
            $scope.tab.display = v;
            $scope.tab.knowledgeId = k; //why tab is enabled
            if (v == 1) {
                dataFactoryCRM.postDataByAPI('Knowledgeproperty/GetTabData', { knowledgeId: $scope.tab.knowledgeId }).then(function(d) {
                    $scope.editparam = d.data;
                    if (d.data.first_page_show == 1) {
                        $('input[name=firsteditcheckbox]').prop('checked', true);
                        $scope.editparam.editcheck = 1;
                    } else {
                        $('input[name=firsteditcheckbox]').prop('checked', false);
                        $scope.editparam.editcheck = 0;
                    }
                    // $scope.editimg.path = d.data.first_page_image;
                    $rootScope.editimage.path = d.data.first_page_image;
                });
                dataFactoryCRM.postDataByAPI('Knowledgeproperty/GetFirstTabFile', { knowledgeId: $scope.tab.knowledgeId }).then(function(_d) {
                    if (!_d.data) {
                        // $scope.fileEdit = [];
                        $rootScope.editfilesparam.fileEdit = [];
                    } else {
                        $rootScope.editfilesparam.fileEdit = _d.data;
                    }
                });
                $scope.knowledgeModelDisplay();
            } else if (v == 2) {
                // 
                dataFactoryCRM.postDataByAPI('Knowledgeproperty/GetSecondTabData', { knowledgeId: $scope.tab.knowledgeId }).then(function(d) {
                    $scope.editparamSecondTab = d.data;
                    $rootScope.secondTabFile.name = d.data.name;
                    $rootScope.secondTabFile.view_path = d.data.secondfilename;
                    $scope.editfile.knowledge_spot_id = d.data.knowledge_spot_id;
                    Object.defineProperties(d.data, {
                        name: {
                            value: d.data.name,
                            writable: true
                        },
                    });
                });
                $scope.secondtabofkonwledge();
            } else {
                // 
                dataFactoryCRM.postDataByAPI('Knowledgeproperty/GetThirdTabData', { knowledgeId: $scope.tab.knowledgeId }).then(function(d) {
                    $scope.thirdparam = d.data;
                    if (d.data.first_page_show == 1) {
                        $("input[name='thirdcheckbox']").prop('checked', true);
                        $scope.thirdparam.urlexpression = 1;
                    } else {
                        $("input[name='thirdcheckbox']").prop('checked', false);
                        $scope.thirdparam.urlexpression = 0;
                    }
                    $rootScope.thirdurlimg.path = d.data.first_page_image;
                });
                $scope.thirdtabofkonwledge();
            }
        }

        // edit knowledgeproperty model display
        $scope.knowledgeModelDisplay = function() {
            $('.ui.edit.modal').modal({
                closable: false,
                observeChanges: true,
                onApprove: function() {
                    var oldfile = new Array();
                    if ($rootScope.editfilesparam.fileEdit.length > 0) {
                        var addfile = new Array();
                        var oldNum = 0;
                        var addNum = 0;
                        for (var i = 0; i < $rootScope.editfilesparam.fileEdit.length; i++) {
                            if ($rootScope.editfilesparam.fileEdit[i].knowledge_file_id) {
                                oldfile[oldNum] = $rootScope.editfilesparam.fileEdit[i];
                                oldNum++;
                            } else {
                                addfile[addNum] = $rootScope.editfilesparam.fileEdit[i];
                                addNum++;
                            }
                        }
                    }
                    var imgurl = $rootScope.editimage.path;
                    $scope.editparam.edituploadimg = imgurl;
                    // console.log($scope.editparam);
                    if ($('#FirstKnowLedge_id').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('Knowledgeproperty/editknowledgeproperty', { editparam: $scope.editparam, original_name: $rootScope.editfilesparam.edit_file_original_name, view_path: $rootScope.editfilesparam.edit_arrfile, oldfile: oldfile }).then(function(_d) {
                            // console.log(_d);
                            if (_d) {
                                $(".ui.small.modal.editOk").modal('show');
                                setTimeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.KnowledgeDatalist(_d.condition);
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                setTimeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        //second tab edit
        $scope.secondtabofkonwledge = function() {
            $('.ui.secondedit.modal').modal({
                closable: false,
                observeChanges: true,
                onApprove: function() {
                    $scope.editparamSecondTab.edituploadfile = $rootScope.secondTabFile.view_path;
                    $scope.editparamSecondTab.filename = $rootScope.secondTabFile.name;
                    if ($('#SecondEditKnowLedge_id').form('is valid') && $scope.editparamSecondTab.edituploadfile && $scope.editparamSecondTab.filename) {
                        dataFactoryCRM.postDataByAPI('Knowledgeproperty/EditSecondTab', $scope.editparamSecondTab).then(function(d) {
                            if (d) {
                                $(".ui.small.modal.editOk").modal('show');
                                setTimeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.KnowledgeDatalist(d.condition);
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                setTimeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                    } else {
                        $('#edit_sty').addClass('ui basic red pointing prompt label transition visible');
                        document.getElementById("edit_sty").innerHTML = '请选择上传文件';
                        return false;
                        return false;
                    }
                }
            }).modal('show');
        }

        // third tab eidt
        $scope.thirdtabofkonwledge = function() {
            $('.ui.thirdedit.modal').modal({
                closable: false,
                observeChanges: true,
                onApprove: function() {
                    var thirdimgurl = $rootScope.thirdurlimg.path
                    $scope.thirdparam.edituploadimg = thirdimgurl;
                    if ($('#ThirdEditKnowLedge_id').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('Knowledgeproperty/EditThirdTab', $scope.thirdparam).then(function(d) {
                            if (d) {
                                $(".ui.small.modal.editOk").modal('show');
                                setTimeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.KnowledgeDatalist(d.condition);
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                setTimeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        // del knowledgeproperty records
        $scope.delknowledge = function(k, v, x) {
            var title = this.knowledge.title;
            $('#knowledgeproperty_del .content p').html("记录【文章标题:" + title + "】确认删除吗？");
            $('.modal3').modal({
                onApprove: function() {
                    dataFactoryCRM.postDataByAPI('Knowledgeproperty/delknowledgerecord', { knowledgeId: k, sign: v, kn: x }).then(function(_d) {
                        $scope.KnowledgeDatalist(_d.condition);
                    });
                }
            }).modal('show');
        }

        // knowledge node tree
        $scope.KnowledgeNodeTree = function(arr) {
            var changArr = [];
            var newArr = ["00"];
            for (var i = 0; i < arr.length; i++) {
                changArr.push(arr[i]['code']);
            }
            for (var i = 1; i < arr.length; i++) {
                if (changArr[i].length > 4) {
                    var num = changArr[i].length - 4;
                    var a = changArr[i].substring(0, changArr[i].length - num);
                    if (changArr.indexOf(a) == -1) {
                        newArr.push(a);
                    } else {
                        newArr.push(changArr[i]);
                    }
                } else {
                    newArr.push(changArr[i]);
                }
            }
            var treeStr = '<div class="ui accordion">'
            for (var i = 0; i < arr.length; i++) {
                if (i == 0) {
                    treeStr += '<div class="active title" ><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length > newArr[i - 1].length) {
                    var time = (newArr[i].length - newArr[i - 1].length) / 2;
                    if (time > 1) {
                        for (var k = 1; k < time; k++) {
                            treeStr += '<div class="active content"><div class="accordion">';
                        }
                    }
                    treeStr += '<div class="active content"><div class="accordion"><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length == newArr[i - 1].length && newArr[i].length != 2) {
                    treeStr += '<div class="active content"></div><div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length == newArr[i - 1].length && newArr[i].length == 2) {
                    treeStr += '<div class="active content"></div><div class="active title"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length < newArr[i - 1].length && newArr[i].length != 2) {
                    treeStr += '<div class="active content"></div>';
                    var num = (newArr[i - 1].length - newArr[i].length) / 2;
                    for (var j = 0; j < num; j++) {
                        treeStr += '</div></div>';
                    }
                    treeStr += '<div class="active title" ng-click="condition(' + arr[i]['knowledge_spot_id'] + ',$event)"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                } else if (newArr[i].length < newArr[i - 1].length && newArr[i].length == 2) {
                    treeStr += '<div class="active content"></div>';
                    var num = (newArr[i - 1].length - newArr[i].length) / 2;
                    for (var j = 0; j < num; j++) {
                        treeStr += '</div></div>';
                    }
                    treeStr += '<div class="active title"><i class="dropdown icon"></i>' + arr[i]['name'] + '</div>';
                }
                if (i == arr.length - 1) {
                    treeStr += '<div class="active content"></div>';
                }
            }
            var $html = $compile(treeStr)($scope);
            $('.treemenu').html($html);
            $(".treemenu .content").each(function() {
                if ($(this).text() == "") {
                    $(this).prev().find(".icon").removeClass('dropdown').addClass('small minus');
                }
            });
            $('.treemenu .ui.accordion').accordion({
                exclusive: false,
                selector: {
                    trigger: '.title .icon'
                }
            });
            $('.treemenu .ui.accordion').find('.accordion').css("marginLeft", "20px");
        }

        // condition judged
        $scope.condition = function(k, $event) {
            $('.treemenu .title').removeClass('checked');
            $($event.target).addClass('checked');
            $scope.tabcondition = k;
            $scope.KnowledgeDatalist();
        }

        // get file name and extension name 
        $scope.GetFileName = function(k) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('Knowledgeproperty/GetFileName?knowledgefileId=' + k).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // download second tab file
        $scope.DownSecondTabFile = function(k) {
            $scope.GetFileName(k).then(function(d) {
                var extensionname = d.extersion;
                var original_name = d.name;
                var _url = 'Knowledgeproperty/DownSecondTabFile?knowledgefileId=' + k;
                dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
                    var blob = new Blob([response], {
                        type: "application/octet-stream"
                    });
                    saveAs(blob, original_name[0] + '.' + extensionname[1]);
                });
            })
        }

        // 
        $scope.operation = function() {
            // console.log(11);
            //分页20条内容，后五条dropdown向上显示
            $('#menu').dropdown();
        }
    });
});